package com.kj.platformlogistics.home.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseActivity;
import com.kj.platformlogistics.constants.UrlConstants;
import com.kj.platformlogistics.home.adapter.TraceAdapter;
import com.kj.platformlogistics.home.adapter.WaitSolicilationDetailAdapter;
import com.kj.platformlogistics.home.model.SolicilationedModel;
import com.kj.platformlogistics.http.HttpRequest;
import com.kj.platformlogistics.http.HttpStringCallBack;
import com.kj.platformlogistics.util.GlideEngine;
import com.kj.platformlogistics.util.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SolicilationedDetailActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rcCommon,rcTrack;
    private WaitSolicilationDetailAdapter adapter;
    private TraceAdapter traceAdapter;
    private ImageView ivTakePicture,ivPicture;
    private LinearLayout llReTake,llTake,llDelete;
    private SolicilationedModel.ResultDTO.PageDTO model;
    private RelativeLayout rlPicture;
    private Boolean isShow=false;

    private TextView tvPostName,tvPostAddress,tvReceiveName,tvReceiveAddress,tvNumber,
    tvOrderNumber,tvPayType,tvOrderCreateTime;

    public static void actionStart(Context context, SolicilationedModel.ResultDTO.PageDTO model) {
        Intent intent = new Intent(context, SolicilationedDetailActivity.class);
        intent.putExtra("model",(Serializable) model);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_solicilationed_detail;
    }

    @Override
    protected void initView() {
        setTitleText("订单详情");
        model=(SolicilationedModel.ResultDTO.PageDTO)getIntent().getSerializableExtra("model");
        rcCommon=findViewById(R.id.rcCommon);
        rlPicture=findViewById(R.id.rlPicture);
        llTake=findViewById(R.id.llTake);
        tvPostName=findViewById(R.id.tvPostName);
        rcTrack=findViewById(R.id.rcTrack);
        llDelete=findViewById(R.id.llDelete);
        ivTakePicture=findViewById(R.id.ivTakePicture);
        ivPicture=findViewById(R.id.ivPicture);
        tvReceiveName=findViewById(R.id.tvReceiveName);
        tvPayType=findViewById(R.id.tvPayType);
        llReTake=findViewById(R.id.llReTake);
        tvReceiveAddress=findViewById(R.id.tvReceiveAddress);
        tvPostAddress=findViewById(R.id.tvPostAddress);
        tvOrderNumber=findViewById(R.id.tvOrderNumber);
        tvOrderCreateTime=findViewById(R.id.tvOrderCreateTime);
        tvNumber=findViewById(R.id.tvNumber);
        rlPicture.setOnClickListener(this::onClick);
        ivPicture.setOnClickListener(this::onClick);
        llReTake.setOnClickListener(this::onClick);
        ivTakePicture.setOnClickListener(this);
        llDelete.setOnClickListener(this::onClick);
        if (model!=null){
            setView();
        }
    }

    public void setView(){
        tvPostName.setText(model.getMailName());
        tvPostAddress.setText(model.getMailAddress());
        tvReceiveName.setText(model.getReceiveName());
        tvReceiveAddress.setText(model.getReceiveAddress());
        tvNumber.setText(model.getNum()+"件");
        tvPayType.setText(model.getPayWay());
        tvOrderCreateTime.setText(model.getCreateTime());
        tvOrderNumber.setText(model.getWaybillNumber());
        if (model.getOrderDetailList().size()>0){
            adapter=new WaitSolicilationDetailAdapter(model.getOrderDetailList());
            rcCommon.setAdapter(adapter);
            rcCommon.setLayoutManager(new LinearLayoutManager(this));
        }

        if (model.getLogisticsStatusList().size()>0){
            traceAdapter=new TraceAdapter(this,model.getLogisticsStatusList());
            rcTrack.setAdapter(traceAdapter);
            rcTrack.setLayoutManager(new LinearLayoutManager(this));
        }

        if (model.getCollectPhoto()==null||model.getCollectPhoto().equals("")){
            //未上传揽件图片
            rlPicture.setVisibility(View.GONE);
            ivTakePicture.setVisibility(View.VISIBLE);
        }else {
            Glide.with(SolicilationedDetailActivity.this)
                    .load(model.getCollectPhoto())
                    .placeholder(R.mipmap.default_image)
                    .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                    .into(ivPicture);
            rlPicture.setVisibility(View.VISIBLE);
            ivTakePicture.setVisibility(View.GONE);
        }
        Log.e("aaaaaa",model.getQrCode());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivPicture:
                if (!isShow){
                    llTake.setVisibility(View.VISIBLE);
                }else {
                    llTake.setVisibility(View.GONE);
                }
                isShow=!isShow;
                break;
            case R.id.llReTake:
            case R.id.ivTakePicture:
                PictureSelector.create(SolicilationedDetailActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .isCamera(true)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .forResult(PictureConfig.REQUEST_CAMERA);
                break;
            case R.id.llDelete:
                deleteImg();
                break;
        }
    }

    private String path="";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.REQUEST_CAMERA:
                    // 结果回调
                    List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if(cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                    }
                    uploadImg(path);
                    break;
                default:
                    break;
            }
        }
    }
    public void uploadImg(String path){
        new HttpRequest(SolicilationedDetailActivity.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Glide.with(SolicilationedDetailActivity.this).load(message)
                                .placeholder(R.mipmap.default_image)
                                .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                                .into(ivPicture);
                        rlPicture.setVisibility(View.VISIBLE);
                        ivPicture.setVisibility(View.VISIBLE);
                        ivTakePicture.setVisibility(View.GONE);
                        submitImg(message);
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void submitImg(String path){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("id",model.getId());
            jsonObject.put("picture",path);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(SolicilationedDetailActivity.this).doPost(UrlConstants.logistics_uploadCollectPhoto, "", jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, "上传车辆图片成功！", 1);
                        toastUtil.show();

                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    public void deleteImg(){
        new HttpRequest(SolicilationedDetailActivity.this).doGet(UrlConstants.logistics_deleteCollectPhoto+model.getId(), "",new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        ivPicture.setVisibility(View.GONE);
                        ivTakePicture.setVisibility(View.VISIBLE);
                        rlPicture.setVisibility(View.GONE);
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }
}